﻿<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>供应商管理</title>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <link rel="stylesheet" href="//unpkg.com/element-plus/dist/index.css" />
    <script src="//unpkg.com/element-plus"></script>
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", Arial, sans-serif;
            background-color: #f5f7fa;
        }

        #tableBlock {
            margin: 20px auto;
            width: 95%;
            padding-bottom: 20px;
            box-shadow: 0 0 10px 4px rgba(0, 0, 0, 0.1);
            background-color: #fff;
            border-radius: 6px;
        }

        .search-area {
            padding: 20px;
            border-bottom: 1px solid #ebeef5;
        }

        .formTableInput, .formTableSelect {
            display: inline-block;
            width: 180px;
        }

        .buttonBlock {
            height: 40px;
            width: 100%;
            padding: 20px;
            gap: 10px;
            margin-bottom: 15px;
            flex-wrap: wrap;
            display: flex;
            align-items: center;
        }

        .pagination-container {
            margin-top: 20px;
            display: flex;
            justify-content: flex-end;
            padding: 0 20px;
            align-items: center;
            gap: 15px;
        }

        .pagination-info {
            color: #606266;
            font-size: 14px;
        }

        .operate-btn {
            margin-right: 12px;
            padding: 0;
            font-size: 14px;
        }

        .edit-btn {
            color: #409eff !important;
        }

        .delete-btn {
            color: #f56c6c !important;
        }

        .el-button--text:hover {
            background-color: transparent !important;
        }

        .btnAndTable {
            margin: 0 auto;
            padding: 0 20px;
        }

        .search-row {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
            margin-bottom: 15px;
        }

        .search-item {
            display: flex;
            align-items: center;
        }

            .search-item label {
                min-width: 80px;
                text-align: right;
                margin-right: 10px;
            }

        .status-tag {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 12px;
            color: #fff;
        }

        .status-enabled {
            background-color: #409eff;
        }

        .status-disabled {
            background-color: #909399;
        }

        .pagination-jumper {
            display: flex;
            align-items: center;
            color: #606266;
            font-size: 14px;
        }

            .pagination-jumper .el-input {
                width: 60px;
                margin: 0 5px;
            }

        .action-column {
            min-width: 150px;
        }

        .table-title {
            font-size: 16px;
            font-weight: 600;
            color: #303133;
            margin: 0 0 15px 0;
            padding: 0 20px;
        }

        .selected-row-count {
            margin-left: 10px;
            color: #409eff;
            font-size: 14px;
        }

        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, 0.8);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 9999;
        }

        .industry-select .el-select-dropdown__wrap {
            max-height: 204px;
            overflow-y: auto;
        }

        .industry-select .el-select-dropdown__item {
            height: 34px;
            line-height: 34px;
            padding: 0 16px;
        }
    </style>
</head>
<body>
    <div id="app" class="common-layout">
        <div id="tableBlock">
            <div class="search-area">
                <h3 class="table-title">供应商管理</h3>
                <div class="search-row">
                    <div class="search-item">
                        <label>供应商：</label>
                        <el-input type="text" v-model="searchForm.supplierName" class="formTableInput" placeholder="请输入供应商名称/编号"></el-input>
                    </div>
                    <div class="search-item">
                        <label>状态：</label>
                        <el-select v-model="searchForm.status" class="formTableSelect" placeholder="请选择状态">
                            <el-option label="全部" value=""></el-option>
                            <el-option label="启用" value="1"></el-option>
                            <el-option label="禁用" value="0"></el-option>
                        </el-select>
                    </div>
                    <div class="search-item">
                        <label>所属行业：</label>
                        <el-select v-model="searchForm.industry"
                                   class="formTableSelect industry-select"
                                   placeholder="请选择所属行业">
                            <el-option v-for="item in industryOptions"
                                       :key="item.value"
                                       :label="item.label"
                                       :value="item.value">
                            </el-option>
                        </el-select>
                    </div>
                    <div class="search-item">
                        <label>联系人：</label>
                        <el-input type="text" v-model="searchForm.contact" class="formTableInput" placeholder="请输入"></el-input>
                    </div>
                    <el-button type="default" @@click="resetForm">重置</el-button>
                    <el-button type="primary" @@click="searchTable">查询</el-button>
                </div>

                <div class="buttonBlock">
                    <el-button type="primary" @@click="addSupplier">新增</el-button>
                    <el-button type="default" @@click="deleteSupplier">删除</el-button>
                    <el-button type="default" @@click="copySupplier">复制</el-button>
                    <el-button type="default" @@click="exportTable">导出</el-button>
                    <el-button type="success" @@click="refreshTable">刷新</el-button>
                    <span class="selected-row-count" v-if="selectedRows.length > 0">
                        已选中 {{ selectedRows.length }} 条
                    </span>
                </div>
            </div>

            <div class="btnAndTable">
                <el-table :data="paginatedData"
                          style="width: 100%; margin-top: 10px"
                          @@selection-change="handleSelectionChange"
                          ref="multipleTable"
                          stripe
                          border>
                    <el-table-column fixed type="selection" width="50"></el-table-column>
                    <el-table-column fixed label="供应商编号" width="150">
                        <template #default="scope">
                            <span style="color: #10b981; cursor: pointer;" @@click="jumpToDetail(scope.row)">
                                {{ scope.row.supplierCode }}
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column fixed prop="supplierName" label="供应商名称" width="180"></el-table-column>
                    <el-table-column fixed prop="status" label="状态" width="100">
                        <template #default="scope">
                            <span :class="['status-tag', getStatusClass(scope.row.status)]">
                                {{ getStatusText(scope.row.status) }}
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="industry" label="所属行业" width="120"></el-table-column>
                    <el-table-column prop="contactPerson" label="联系人" width="120"></el-table-column>
                    <el-table-column prop="contactPhone" label="联系电话" width="130"></el-table-column>
                    <el-table-column prop="email" label="电子邮箱" width="180"></el-table-column>
                    <el-table-column prop="address" label="供应商地址" width="220" show-overflow-tooltip></el-table-column>
                    <el-table-column prop="openingBank" label="开户行" width="150"></el-table-column>
                    <el-table-column prop="bankAccount" label="银行账号" width="180"></el-table-column>
                    <el-table-column prop="taxpayerId" label="纳税人识别号" width="180"></el-table-column>
                    <el-table-column prop="bankAddress" label="银行地址" width="220" show-overflow-tooltip></el-table-column>
                    <el-table-column prop="createBy" label="创建人" width="100"></el-table-column>
                    <el-table-column label="创建时间" width="160">
                        <template #default="scope">
                            {{ formatDateTime(scope.row.createTime) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="更新时间" width="160">
                        <template #default="scope">
                            {{ formatDateTime(scope.row.updateTime) }}
                        </template>
                    </el-table-column>

                    <el-table-column fixed="right" label="操作" min-width="120" class="action-column">
                        <template #default="scope">
                            <el-button class="operate-btn edit-btn"
                                       type="text"
                                       @@click="handleEdit(scope.row)">
                                编辑
                            </el-button>
                            <el-button class="operate-btn delete-btn"
                                       type="text"
                                       @@click="deleteSingleSupplier(scope.row)">
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <div class="pagination-container">
                    <div class="pagination-info">
                        共 {{ total }} 条
                        <el-select v-model="pageSize"
                                   size="mini"
                                   style="width: 100px; margin: 0 5px;"
                                   @@change="handleSizeChange">
                            <el-option label="10条/页" :value="10"></el-option>
                            <el-option label="20条/页" :value="20"></el-option>
                            <el-option label="50条/页" :value="50"></el-option>
                            <el-option label="100条/页" :value="100"></el-option>
                        </el-select>
                    </div>

                    <el-pagination v-model:current-page="currentPage"
                                   v-model:page-size="pageSize"
                                   :total="total"
                                   layout="prev, pager, next"
                                   :pager-count="5"
                                   @@current-change="handleCurrentChange">
                    </el-pagination>

                    <div class="pagination-jumper">
                        <span>前往</span>
                        <el-input v-model.number="jumpPage"
                                  size="mini"
                                  @@keyup.enter="handleJump">
                        </el-input>
                        <span>页</span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        const { createApp, ref, onMounted, computed, watch } = Vue;
        const { ElMessageBox, ElMessage, ElNotification } = ElementPlus;

        const STATUS_CONFIG = {
            0: { text: '禁用', class: 'status-disabled' },
            1: { text: '启用', class: 'status-enabled' }
        };

        const industryOptions = [
            { label: '零售', value: '零售' },
            { label: '制造', value: '制造' },
            { label: '制药厂', value: '制药厂' },
            { label: '工程', value: '工程' },
            { label: '原厂商', value: '原厂商' },
            { label: '服务商', value: '服务商' },
            { label: '代理商', value: '代理商' },
            { label: '金融业', value: '金融业' },
            { label: '教育', value: '教育' },
            { label: '医疗', value: '医疗' },
            { label: '互联网', value: '互联网' },
            { label: '传媒', value: '传媒' }
        ];

        const app = createApp({
            setup() {
                const searchForm = ref({
                    supplierName: '',
                    status: '',
                    industry: '',
                    contact: ''
                });

                const tableData = ref([]);
                const selectedRows = ref([]);
                const multipleTable = ref(null);
                const loading = ref(false);

                const currentPage = ref(1);
                const pageSize = ref(10);
                const jumpPage = ref(1);
                const total = computed(() => tableData.value.length);
                const originalData = ref([]);

                watch(currentPage, (val) => {
                    jumpPage.value = val;
                }, { flush: 'sync' });

                const paginatedData = computed(() => {
                    const start = (currentPage.value - 1) * pageSize.value;
                    const end = start + pageSize.value;
                    return tableData.value.slice(start, end);
                });

                const handleSizeChange = (val) => {
                    pageSize.value = val;
                    currentPage.value = 1;
                };

                const handleCurrentChange = (val) => {
                    currentPage.value = val;
                    if (multipleTable.value) {
                        multipleTable.value.clearSelection();
                        selectedRows.value = [];
                    }
                };

                const handleJump = () => {
                    let page = parseInt(jumpPage.value);
                    if (isNaN(page) || page < 1) {
                        page = 1;
                    }
                    const maxPage = Math.ceil(total.value / pageSize.value) || 1;
                    if (page > maxPage) {
                        page = maxPage;
                    }

                    if (page !== currentPage.value) {
                        currentPage.value = page;
                    } else {
                        jumpPage.value = page;
                    }
                };

                const getStatusText = (status) => STATUS_CONFIG[status]?.text || '未知状态';
                const getStatusClass = (status) => STATUS_CONFIG[status]?.class || '';

                const handleSelectionChange = (val) => {
                    selectedRows.value = val;
                };

                const handleEdit = (row) => {
                    window.location.href = `/BiSupplier/Edit?id=${row.supplierId}`;
                };

                const deleteSingleSupplier = async (row) => {
                    try {
                        await ElMessageBox.confirm(
                            `确定删除供应商 "${row.supplierName}" 吗？删除后不可恢复！`,
                            '警告',
                            { type: 'error', confirmButtonText: '确定', cancelButtonText: '取消' }
                        );
                        loading.value = true;
                        const response = await axios.post(`/BiSupplier/Delete?id=${row.supplierId}`);
                        if (response.data.code === 200) {
                            ElMessage.success('删除成功！');
                            await refreshData();
                        } else {
                            ElMessage.error(`删除失败：${response.data.msg || '未知错误'}`);
                        }
                    } catch (error) {
                        if (error !== 'cancel') ElMessage.error('删除失败，请重试');
                    } finally {
                        loading.value = false;
                    }
                };

                const deleteSupplier = async () => {
                    if (selectedRows.value.length === 0) {
                        ElMessage.warning('请先选中需要删除的供应商！');
                        return;
                    }
                    const deleteNames = selectedRows.value.map(row => row.supplierName).join('、');
                    const deleteIds = selectedRows.value.map(row => row.supplierId);
                    try {
                        await ElMessageBox.confirm(
                            `确定删除选中的 ${selectedRows.value.length} 条供应商吗？\n${deleteNames}`,
                            '警告',
                            { type: 'error', confirmButtonText: '确定', cancelButtonText: '取消' }
                        );
                        loading.value = true;
                        const results = await Promise.allSettled(
                            deleteIds.map(id => axios.post(`/BiSupplier/Delete?id=${id}`))
                        );
                        let successCount = 0, errorCount = 0;
                        results.forEach(result => {
                            if (result.status === 'fulfilled' && result.value.data.code === 200) {
                                successCount++;
                            } else {
                                errorCount++;
                            }
                        });

                        await refreshData();

                        if (successCount > 0 && errorCount === 0) {
                            ElMessage.success(`全部删除成功，共 ${successCount} 条`);
                        } else if (successCount > 0 && errorCount > 0) {
                            ElMessage.warning(`部分删除成功（${successCount}条），${errorCount}条失败`);
                        } else {
                            ElMessage.error(`全部删除失败，共 ${errorCount} 条`);
                        }
                        selectedRows.value = [];
                        multipleTable.value?.clearSelection();
                    } catch (error) {
                        if (error !== 'cancel') ElMessage.error('删除流程中断，请重试');
                    } finally {
                        loading.value = false;
                    }
                };

                const formatDateTime = (date) => {
                    if (!date) return '';
                    const dt = new Date(date);
                    return `${dt.getFullYear()}-${(dt.getMonth() + 1).toString().padStart(2, '0')}-${dt.getDate().toString().padStart(2, '0')} ${dt.getHours().toString().padStart(2, '0')}:${dt.getMinutes().toString().padStart(2, '0')}:${dt.getSeconds().toString().padStart(2, '0')}`;
                };

                const jumpToDetail = (row) => {
                    ElMessage.info(`跳转至供应商 ${row.supplierCode} 的详情页`);
                };

                const exportTable = async () => {
                    if (selectedRows.value.length === 0) {
                        ElMessage.warning('请先选中需要导出的供应商！');
                        return;
                    }
                    try {
                        loading.value = true;
                        const supplierIds = selectedRows.value.map(row => row.supplierId);

                        const response = await axios({
                            url: '/BiSupplier/Export',
                            method: 'post',
                            data: supplierIds,
                            responseType: 'blob'
                        });

                        const blob = new Blob([response.data], {
                            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                        });
                        const url = window.URL.createObjectURL(blob);
                        const a = document.createElement('a');
                        a.href = url;
                        const fileName = response.headers['content-disposition']
                            ? decodeURIComponent(response.headers['content-disposition'].split('=')[1])
                            : `供应商数据_${new Date().getTime()}.xlsx`;
                        a.download = fileName;
                        document.body.appendChild(a);
                        a.click();

                        window.URL.revokeObjectURL(url);
                        document.body.removeChild(a);

                        ElMessage.success(`导出成功！共导出${selectedRows.value.length}条数据`);
                    } catch (error) {
                        ElMessage.error(`导出失败：${error.response?.data?.msg || '网络错误'}`);
                    } finally {
                        loading.value = false;
                    }
                };

                const refreshTable = () => {
                    multipleTable.value?.clearSelection();
                    selectedRows.value = [];
                    currentPage.value = 1;
                    refreshData();
                    ElMessage.success('表格已刷新！');
                };

                const resetForm = () => {
                    searchForm.value = {
                        supplierName: '',
                        status: '',
                        industry: '',
                        contact: ''
                    };
                    refreshTable();
                };

                const searchTable = () => {
                    const { supplierName, status, industry, contact } = searchForm.value;
                    const filteredData = originalData.value.filter(row => {
                        const matchName = supplierName ? (row.supplierName.includes(supplierName) || row.supplierCode.includes(supplierName)) : true;
                        const matchStatus = status ? row.status === status : true;
                        const matchIndustry = industry ? row.industry === industry : true;
                        const matchContact = contact ? row.contactPerson.includes(contact) : true;
                        return matchName && matchStatus && matchIndustry && matchContact;
                    });
                    tableData.value = filteredData;
                    currentPage.value = 1;
                    ElMessage.success(`查询到 ${filteredData.length} 条数据！`);
                };

                const addSupplier = () => {
                    window.location.href = '/BiSupplier/Create';
                };

                const copySupplier = async () => {
                    if (selectedRows.value.length === 0) {
                        ElMessage.warning('请先选中需要复制的供应商！');
                        return;
                    }

                    try {
                        let copyContent = "供应商编号\t供应商名称\t状态\t所属行业\t联系人\t联系电话\t电子邮箱\n";

                        selectedRows.value.forEach(row => {
                            const statusText = row.status === "1" ? "启用" : "禁用";
                            copyContent += `${row.supplierCode}\t${row.supplierName}\t${statusText}\t${row.industry}\t${row.contactPerson}\t${row.contactPhone}\t${row.email}\n`;
                        });

                        await navigator.clipboard.writeText(copyContent);

                        ElMessage.success(`复制成功！共复制${selectedRows.value.length}条供应商数据`);
                    } catch (error) {
                        ElMessage.error('复制失败，请手动复制或刷新页面重试');
                    }
                };

                const refreshData = async () => {
                    if (loading.value) return;
                    try {
                        loading.value = true;
                        const response = await axios.post('/BiSupplier/GetAll');
                        if (response.data.code === 200) {
                            const processedData = response.data.data.map(item => {
                                if (typeof item.industry === 'number') {
                                    const industryIndex = item.industry - 1;
                                    if (industryIndex >= 0 && industryIndex < industryOptions.length) {
                                        item.industry = industryOptions[industryIndex].value;
                                    }
                                }
                                return item;
                            });

                            originalData.value = processedData;
                            tableData.value = processedData;
                        } else {
                            ElMessage.error(response.data.msg || '数据加载失败');
                        }
                    } catch (error) {
                        ElMessage.error('数据加载失败，请重试');
                    } finally {
                        loading.value = false;
                    }
                };

                onMounted(() => {
                    refreshData();
                });

                return {
                    searchForm,
                    tableData,
                    paginatedData,
                    selectedRows,
                    multipleTable,
                    loading,
                    handleSelectionChange,
                    handleEdit,
                    deleteSingleSupplier,
                    getStatusText,
                    getStatusClass,
                    currentPage,
                    pageSize,
                    jumpPage,
                    total,
                    handleSizeChange,
                    handleCurrentChange,
                    handleJump,
                    industryOptions,
                    addSupplier,
                    deleteSupplier,
                    copySupplier,
                    exportTable,
                    refreshTable,
                    resetForm,
                    searchTable,
                    formatDateTime,
                    jumpToDetail
                };
            }
        });

        app.use(ElementPlus);
        app.mount('#app');
    </script>
</body>
</html>